package com.sinosoft.sinopay.apiservice.batchpay.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.allinpay.XmlTools;
import com.sinosoft.sinocloud.platform.base.SinoBaseService;
import com.sinosoft.sinocloud.platform.common.util.DateUtil;
import com.sinosoft.sinocloud.platform.common.util.XStreamComponent;
import com.sinosoft.sinopay.apiservice.batchpay.dto.PayTradeMainDTO;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqBody;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqInfo;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqTransDetail;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqTransDetails;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqTransSum;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayReqXml;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResBody;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResInfo;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResRetDetail;
import com.sinosoft.sinopay.apiservice.batchpay.dto.TLPayResXml;
import com.sinosoft.sinopay.apiservice.batchpay.util.AmountTransUtil;
import com.sinosoft.sinopay.apiservice.batchpay.util.PropertiesUtils;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeReqDTO;
import com.sinosoft.sinopay.paytrade.facade.PaymentTradeFacadeService;

/**
 * 【 通联支付数据批扣处理 】
 *
 * @author chenzhiheng
 * @version V1.0
 * @date 17/1/4
 */
public class HandTLPayS extends SinoBaseService{

    @Autowired
    private PaymentTradeFacadeService paymentTradeFacadeService;

    /**
     * 通联支付数据处理实现
     *@return
     */
    public void handTLPayDate(List<PayTradeMainDTO> payTradeMainDTOList ,PaymentTradeReqDTO paymentBatch) {
        try {
            PaymentTradeReqDTO paymentMainTrade = new PaymentTradeReqDTO();
            PaymentTradeReqDTO paymentMain = new PaymentTradeReqDTO();
            TLPayReqXml tlPayReqXml = new TLPayReqXml();
            TLPayReqInfo tlPayReqInfo = new TLPayReqInfo();
            TLPayReqTransDetails tlPayReqTransDetails = new TLPayReqTransDetails();
            TLPayReqBody tlPayReqBody = new TLPayReqBody();
            TLPayReqTransSum tlPayReqTransSum = new TLPayReqTransSum();
            String tPath = "/config/allinpayConfig.properties";
            Properties properties = PropertiesUtils.readProperties(tPath);
            tlPayReqInfo.setTRX_CODE(properties.getProperty("TRX_CODE_S")); // 报文头
            tlPayReqInfo.setVERSION(properties.getProperty("VERSION"));
            tlPayReqInfo.setLEVEL(properties.getProperty("LEVEL")); // 处理级别
            tlPayReqInfo.setDATA_TYPE(properties.getProperty("DATA_TYPE"));
            tlPayReqInfo.setUSER_NAME(properties.getProperty("USER_NAME"));
            tlPayReqInfo.setUSER_PASS(properties.getProperty("USER_PASS"));
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
            String dateNow = df.format(date);
            tlPayReqInfo.setREQ_SN("1377051780610" + dateNow); // 交易流水号 商户ID+系统时间
            tlPayReqInfo.setSIGNED_MSG(""); // 签名信息
            tlPayReqXml.setINFO(tlPayReqInfo);

            tlPayReqTransSum.setBUSINESS_CODE(properties.getProperty("BUSINESS_CODE"));
            tlPayReqTransSum.setMERCHANT_ID(properties.getProperty("MERCHANT_ID"));
            tlPayReqTransSum.setSUBMIT_TIME(dateNow);
            tlPayReqTransSum.setTOTAL_ITEM(String.valueOf(payTradeMainDTOList.size()));
            if(paymentBatch.getSumAmount()==null||"".equals(paymentBatch.getSumAmount())){
            	throw new Exception("总金额不能为空");
            }
            AmountTransUtil aAmountTransUtil = new AmountTransUtil();
            System.out.println("money="+paymentBatch.getSumAmount());
            String money = aAmountTransUtil.transAmount(paymentBatch.getSumAmount());
            tlPayReqTransSum.setTOTAL_SUM(money);
            tlPayReqBody.setTRANS_SUM(tlPayReqTransSum);
            List<TLPayReqTransDetail> tlPayReqTransDetailList = new ArrayList<TLPayReqTransDetail>();
            for (int i = 0; i < payTradeMainDTOList.size(); i++) {
                TLPayReqTransDetail tlPayReqTransDetail = new TLPayReqTransDetail();
                tlPayReqTransDetail.setACCOUNT_NAME(payTradeMainDTOList.get(i).getAccountName());
                tlPayReqTransDetail.setACCOUNT_NO(payTradeMainDTOList.get(i).getAccountNo());
                tlPayReqTransDetail.setACCOUNT_PROP(Integer.parseInt(properties.getProperty("ACCOUNT_PROP")));
                tlPayReqTransDetail.setACCOUNT_TYPE(properties.getProperty("ACCOUNT_TYPE"));
                //TODO
                String tAmount = aAmountTransUtil.transAmount(payTradeMainDTOList.get(i).getPayAmount());
                tlPayReqTransDetail.setAMOUNT(tAmount);
                tlPayReqTransDetail.setBANK_CODE("105");
                tlPayReqTransDetail.setBANK_NAME("");
                tlPayReqTransDetail.setCITY("");
                tlPayReqTransDetail.setCURRENCY(properties.getProperty("CURRENCY"));
                tlPayReqTransDetail.setCUST_USERID("");
                tlPayReqTransDetail.setE_USER_CODE("");
                tlPayReqTransDetail.setID("");
                tlPayReqTransDetail.setID_TYPE("");
                tlPayReqTransDetail.setPROTOCOL("");
                tlPayReqTransDetail.setPROTOCOL_USERID("");
                tlPayReqTransDetail.setPROVINCE("");
                tlPayReqTransDetail.setREMARK("");
                tlPayReqTransDetail.setSETTACCT("");
                tlPayReqTransDetail.setSN((i + 1));
                tlPayReqTransDetail.setTEL("");
                tlPayReqTransDetailList.add(tlPayReqTransDetail);
            }
            tlPayReqBody.setTRANS_DETAILS(tlPayReqTransDetailList);
            tlPayReqXml.setBODY(tlPayReqBody);
            XStreamComponent xstream = new XStreamComponent();
            xstream.processAnnotations(new Class[]{TLPayReqBody.class, TLPayReqInfo.class, TLPayReqTransDetail.class,
                     TLPayReqTransSum.class, TLPayReqXml.class, TLPayResBody.class
                    , TLPayResInfo.class, TLPayResRetDetail.class,  TLPayResXml.class});
            String reqXml = "<?xml version=\"1.0\" encoding=\"GBK\"?>" + xstream.toXML(tlPayReqXml).replace("__", "_");
            logger.info("请求报文：" + reqXml.toString());
            String url = properties.getProperty("SERVER_URL");
            String signData = this.isFront(reqXml,false,url);
            //解析返回报文
            TLPayResXml response = (TLPayResXml) xstream.fromXML(signData);
            String returnCode = response.getINFO().getRET_CODE();
            List<TLPayResRetDetail> tlResList ;
            if(returnCode!=null && returnCode.equals("0000")){
                tlResList = response.getBODY().getRET_DETAILS();
                for(int i = 0; i < tlResList.size() ; i++){
                    for(int j = 0; j < tlPayReqTransDetailList.size(); j++){
                        if(tlResList.get(i).getSN() == tlPayReqTransDetailList.get(j).getSN()) {
                            paymentMain.setBatchNo(paymentBatch.getBatchNo());
                            paymentMain.setReturnTime(DateUtil.getCurrentDate());
                            paymentMain.setResultCode(tlResList.get(i).getRET_CODE());
                            paymentMain.setResultDesc(tlResList.get(i).getERR_MSG());
                            int resultMain = paymentTradeFacadeService.modifyPaymentInfo(paymentMain);
                            if (resultMain < 1) {
                                throw new Exception("修改支付交易数据关联表失败!");
                            }

                            paymentMainTrade.setBatchNo(paymentBatch.getBatchNo());
                            paymentMainTrade.setResultCode(tlResList.get(i).getRET_CODE());
                            paymentMainTrade.setResultDesc(tlResList.get(i).getERR_MSG());
                            int resultMainTrade = paymentTradeFacadeService.modifyTransePayRelate(paymentMainTrade);
                            if (resultMainTrade < 1) {
                                throw new Exception("修改支付交易数据失败!");
                            }
                        }
                    }
                }
            }else{
                logger.error("通联批扣请求有误!");
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            logger.error("通联批扣出错");
        }
    }

    public String sendXml(String xml,String url,boolean isFront) throws UnsupportedEncodingException, Exception{
        System.out.println("======================发送报文======================：\n"+xml);
        String resp= XmlTools.send(url,new String(xml.getBytes(),"GBK"));
        System.out.println("======================响应内容======================") ;
        String tPath = "/config/allinpayConfig.properties";
        Properties properties = PropertiesUtils.readProperties(tPath);
        String rootPath = this.getClass().getResource("/").getPath().toString();
        String pathPfx = rootPath + properties.getProperty("TLTCERPATH");
        boolean flag= this.verifyMsg(resp, pathPfx,isFront);
        if(flag){
            System.out.println("响应内容验证通过") ;
        }else{
            System.out.println("响应内容验证不通过") ;
        }
        return resp;
    }

    public String isFront(String xml,boolean flag,String url) {
        try{
            if(!flag){
                xml=this.signMsg(xml);
            }else{
                xml=xml.replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");
            }
            return sendXml(xml,url,flag);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 报文签名
     * @param
     * @return
     *日期：Sep 9, 2012
     * @throws Exception
     */
    public String signMsg(String xml) throws Exception{
        String tPath = "/config/allinpayConfig.properties";
        Properties properties = PropertiesUtils.readProperties(tPath);
        String rootPath = this.getClass().getResource("/").getPath().toString();
        String pathPfx = rootPath + properties.getProperty("PFXPATH");
        xml=XmlTools.signMsg(xml, pathPfx,properties.getProperty("TLPASS"), false);
        return xml;
    }

    /**
     * 验证签名
     * @param msg
     * @return
     *日期：Sep 9, 2012
     * @throws Exception
     */
    public boolean verifyMsg(String msg,String cer,boolean isFront) throws Exception{
        boolean flag=XmlTools.verifySign(msg, cer, false,isFront);
        System.out.println("验签结果["+flag+"]") ;
        return flag;
    }

}
